package com.zlp.netty.lecture;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.util.Scanner;

/**
 * @author: zhulaiping
 * @time: 2022/9/6 11:42
 */
@Slf4j
public class EchoClient {

    public static void main(String[] args) throws InterruptedException {
        Channel channel = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<Channel>() {
                    @Override
                    protected void initChannel(Channel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());
                        ch.pipeline().addLast(new StringDecoder());
                        ch.pipeline().addLast(new SimpleChannelInboundHandler<String>() {
                            @Override
                            protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
                                log.debug("收到服务端发来信息：{}",msg);
                                //ctx.fireChannelRead(msg);
                                //向channel中写入数据传递给客户端，若是channel调用，就直接从tail处开始向前查询出战处理器
                            }
                        });
                    }
                })
                .connect("localhost", 8080)
                .sync()
                .channel();
        new Thread(()->{
            Scanner scanner = new Scanner(System.in);
            while (true){
                String line = scanner.nextLine();
                channel.writeAndFlush(line);
                if("q".equals(line)) {
                    channel.closeFuture();
                    break;
                }
            }
        }).start();

    }
}
